import { defineStore } from 'pinia';
/* eslint-disable no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { postSysPermissionTree } from '@/api/userCenter';
import { asyncRouterMap, constRouterMap } from '@/router';
import { cloneDeep } from 'lodash';
import config from '@/config';
import { useStoreUser } from '@/store';
//  方法
import { isEmpty } from '@/utils/tools';

// 后端路由树转一维数组
function localTreeForeach(tree, obj = {}) {
  tree.forEach(item => {
    const i = Object.assign({}, item);
    // delete i.children;
    obj[item.perms] = i;
    let children = item.childrenList?.filter((ele) => {
      return ele.menuType != "F";
    });
    if (children && children.length > 0) {
      localTreeForeach(children, obj);
    }
  });
  return obj;
}

//  后端路由树处理
function exchangeTreeData(tree) {
  let resultTree = [];
  tree.forEach((item) => {
    // 按钮
    let operationPermissions = item.childrenList?.filter((ele) => {
      return ele.menuType == "F";
    });
    // 非按钮
    let children = item.childrenList?.filter((ele) => {
      return ele.menuType != "F";
    });
    let curComponent = {
      ...item,
      operationPermissions,
    };
    // debugger
    curComponent.children = exchangeTreeData(children);
    resultTree.push(curComponent);
  });
  return resultTree;
}

function findRoutePower(data = [], operationPermissions = {}) {
  for (let i = 0; i < data.length; i++) {
    const item = data[i];
    if (item.perms) {
      if (item.operationPermissions) {
        operationPermissions[item.perms] = item.operationPermissions.map(item => ({
          ...item,
          permissionName: item.perms
        }));
      }
    }
    if (item.children) {
      findRoutePower(item.children, operationPermissions);
    }
  }
  return operationPermissions;
}

// 前端路由树和后端路由匹配，合并所需参数，返回过滤后的路由树。
function resetTreeData(treeData, routerList) {
  // debugger
  let resultTree = [];
  treeData.forEach(item => {
    let curComponent = {}
    if (item.meta.toRoute) {
      curComponent = Object.assign({}, item);
      delete curComponent.children
    } else {
      const obj = routerList[item.name] || {};
      if (JSON.stringify(obj) != '{}') {
        console.log('obj', obj);
        console.log('item', item);
        item.meta.title = obj.menuName
        curComponent = Object.assign({}, item);
        delete curComponent.children
      }
    }
    // debugger
    if (JSON.stringify(curComponent) != '{}') {
      if (item.children) {
        const childrenList = resetTreeData(item.children, routerList)
        curComponent.children = childrenList;
      }
      resultTree.push(curComponent);
    }
  });

  return resultTree;

}




// 重置state函数
const getDefaultState = () => {
  return {
    curRoute: {},
    powers: {}, // 按钮权限
    addRouters: [],
    menuList: [],
  };
};

const defalutState = getDefaultState();

export const useStorePermission = defineStore('permission', () => {
  let state = reactive(defalutState);

  function GenerateRoutes() {
    const routerMap = cloneDeep(asyncRouterMap);
    return new Promise(resolve => {
      if (config.asyncRoutes) {
        const storeUser = useStoreUser();
        if (storeUser.userInfo.username == 'admin') {
          routerMap[0].children = [...constRouterMap, ...routerMap[0].children];
          state.addRouters = routerMap;
          state.menuList = routerMap[0].children || [];
          resolve(routerMap);
        } else {
        }
        postSysPermissionTree().then(res => {
          let resultData = res.data;
          resultData = exchangeTreeData(resultData)
          const obj = localTreeForeach(resultData);
          const routerTree = resetTreeData(routerMap[0].children, obj);
          const power = findRoutePower(resultData);
          const menuList = [...constRouterMap, ...routerTree];
          routerMap[0].children = menuList
          state.addRouters = menuList;
          state.powers = power;
          state.menuList = menuList;
          resolve(routerMap);
        });
      } else {
        // debuggers
        routerMap[0].children = [...constRouterMap, ...routerMap[0].children];
        state.addRouters = routerMap;
        state.menuList = routerMap[0].children || [];
        resolve(routerMap);
      }
    });
  }

  // 修改state值
  const changeValue = (type, value) => {
    state[type] = value;
  };

  const resetValue = () => {
    Object.assign(state, getDefaultState());
  };

  return {
    GenerateRoutes,
    changeValue,
    resetValue,
    ...toRefs(state),
  };
});
